package org.example.ims.Utils;


import jakarta.persistence.criteria.Predicate;
import org.example.ims.Entity.WareHouseProduct.WarehouseProduct;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;

public class WarehouseProductSpecifications {
    // 采用另一种方式实现WP查询逻辑的方法
    public static Specification<WarehouseProduct> buildSpecification(Integer warehouseId,
                                                                     Integer productId,
                                                                     Integer minStock,
                                                                     Integer maxStock) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 添加复合主键条件
            if (warehouseId != null) {
                predicates.add(cb.equal(root.get("id").get("warehouseId"), warehouseId));
            }
            if (productId != null) {
                predicates.add(cb.equal(root.get("id").get("productId"), productId));
            }

            // 添加库存范围条件
            if (minStock != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("quantity"), minStock));
            }
            if (maxStock != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("quantity"), maxStock));
            }

            // 如果没有指定任何条件，则返回一个始终为真的谓词
            if (predicates.isEmpty()) {
                return cb.isTrue(cb.literal(true));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }
}
